package com.zfl.init;

import com.zfl.entity.Permission;
import com.zfl.mapper.PermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PermUrlInitRunner implements CommandLineRunner {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String PERM_URL_BIT_KEY = "perm:url:bit";

    @Override
    public void run(String... args) {
        // 步骤1：先删除Redis中旧的权限URL映射数据
        if (redisTemplate.hasKey(PERM_URL_BIT_KEY)) {
            redisTemplate.delete(PERM_URL_BIT_KEY);
            log.info("已清除Redis中旧的接口权限映射数据（Key={}）", PERM_URL_BIT_KEY);
        }

        List<Permission> perms = permissionMapper.selectAll();
        Map<String, Integer> urlBitMap = perms.stream()
                .collect(Collectors.toMap(Permission::getUrl, Permission::getBitPosition));
        redisTemplate.opsForHash().putAll(PERM_URL_BIT_KEY, urlBitMap);
        log.info("接口权限映射已缓存到Redis，共{}条", perms.size());
    }
}